<?php
/**
 * h5活动配置类
 */
class Promotional_activityApp extends BackendApp
{
    var $_promotional_activity_mod;
    var $_group_goods_mod;
    var $_activity_group_mod;

    function __construct()
    {
        $this->PromotionalActivityApp();
    }
    function PromotionalActivityApp()
    {
        parent::BackendApp();
        $this->_promotional_activity_mod =& m('promotional_activity');
        $this->_group_goods_mod =& m('group_goods');
        $this->_activity_group_mod =& m('activity_group');
    }


    function index(){
        $conditions = '';
        // 处理分页
        $page = $this->_get_page(20);
        $list = $this->_promotional_activity_mod->find(array(
            'conditions'=>"1=1".$conditions,
            'limit' => $page['limit'],
        ));
        $page['item_count'] = $this->_promotional_activity_mod->getCount();
        foreach($list as $k=>&$v){
            $v['banner_url'] = WEB_PHOTO_SRC.'/'.$v['banner_url'];
            $list[$k]['groupList'] = $this->_activity_group_mod->find(array("conditions"=>"activity_id =".$v['activity_id']));
            if(!empty($list[$k]['groupList'])){
                foreach($list[$k]['groupList'] as $key=>$value){
                    $list[$k]['groupList'][$key]['group_url'] = WEB_PHOTO_SRC.'/'.$value['group_url'];
                }
            }
        }
        $this->_format_page($page);
        $this->assign('filtered', $conditions ? 1 : 0); //是否有查询条件
        $this->assign('page_info', $page);
        $this->assign('list', $list);
        // 引入前端资源
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        // 显示模板
        $this->display('promotional_activity.list.html');
    }
    //添加时间内活动
    function add(){
        if(IS_POST){
            if($_FILES['banner_url']['error'] == 4 || $_FILES['banner_url']['size'] == 0){
                $this->show_message('请上传图片！');
                return false;
            }
            if($_POST['start_time'] >= $_POST['end_time'] || !$_POST['start_time'] || !$_POST['end_time']){
                $this->show_message('时间格式错误！');
                return false;
            }
            $data['start_time'] = strtotime($_POST['start_time']);
            $data['end_time']   = strtotime($_POST['end_time']);

            if (!$activity_id = $this->_promotional_activity_mod->add($data)) {  //获取activity_id
                $this->show_warning($this->_promotional_activity_mod->get_error());
                return;
            } else {
                $this->admin_log("新增banner H5活动", 1);
            }
            //处理上传的文章LOGO
            $article_logo = $this->_upload($_FILES,'banner_url');
            if ($article_logo === false) {
                return;
            }
            $article_logo && $this->_promotional_activity_mod->edit($activity_id, array('banner_url' => $article_logo)); //将logo地址记下
            $this->show_message('添加成功！', '返回列表', 'index.php?app=promotional_activity', '继续添加', 'index.php?app=promotional_activity&amp;act=add'
            );
        }else{
            $this->display("promotional_activity.form.html");
        }
    }

    //编辑
    function view(){
        $activity_id = isset($_GET['activity_id']) ? intval($_GET['activity_id']) : 0;
        if (!$activity_id)
        {
            $this->show_warning('no_such_banner');
            return;
        }
        if (!IS_POST)
        {

            $find_data = $this->_promotional_activity_mod->get($activity_id);
            $find_data['banner_url'] = WEB_PHOTO_SRC.'/'.$find_data['banner_url'];
            if (empty($find_data))
            {
                $this->show_warning('no_such_banner');
                return;
            }
            $this->assign('info', $find_data);
            $this->display('promotional_activity.form.html');
        }
        else
        {
            $find_data     = $this->_promotional_activity_mod->find($activity_id);
            if (empty($find_data))
            {
                $this->show_warning('no_such_banner');
                return;
            }

            //删除原图片
            if($_FILES['banner_url'] && $find_data['banner_url'] && $find_data['banner_url'] != $_FILES['banner_url']){
                if(file_exists(site_url() . '/' . $find_data['banner_url'])){
                    unlink(site_url() . '/' . $find_data['banner_url']);
                }
            }

            $data = array(
                'start_time' => strtotime($_POST['start_time']),
                'end_time'   => strtotime($_POST['end_time'])
            );
            $logo =   $this->_upload($_FILES,'banner_url');
            $logo && $data['banner_url'] = $logo;
            if ($logo === false)
            {
                $this->show_message('请上传图片！');
                return;
            }
            $rows=$this->_promotional_activity_mod->edit($activity_id, $data);
            if ($this->_promotional_activity_mod->has_error())
            {
                $this->show_warning($this->_promotional_activity_mod->get_error());
                return;
            }else{
                $this->admin_log("编辑活动H5",1);
            }
            $this->show_message('编辑成功',
                'back_list',        'index.php?app=promotional_activity',
                'edit_again',    'index.php?app=promotional_activity&amp;act=view&amp;activity_id=' . $activity_id);
        }
    }

    //删除
    function drop(){
        $activity_id = isset($_GET['activity_id']) ? intval($_GET['activity_id']) : 0;
        if (!$activity_id)
        {
            $this->show_warning('no_such_banner');
            return;
        }
        $info = $this->_promotional_activity_mod->get(intval($activity_id));
        //删除原图片
        if($info['banner_url']){
            if(file_exists(site_url() . '/' . $info['banner_url'])){
                unlink(site_url() . '/' . $info['banner_url']);
            }
        }

        if (!$this->_promotional_activity_mod->drop($activity_id)) {    //删除
            $this->show_warning($this->_promotional_activity_mod->get_error());
            return;
        }else{

            $sql = "SELECT * from ecm_activity_group where activity_id = ".$activity_id;
            $resOld1 = $this->_activity_group_mod->db->query($sql);
            while ($chat1 = $this->_activity_group_mod->db->fetchRow($resOld1)) {
                $group_list[] = $chat1;
            }
            foreach ($group_list as $key => $v) {
                $article = $this->_activity_group_mod->find(intval($v['activity_group_id']));
                //删除原图片
                if($v['group_url']){
                    if(file_exists(site_url() . '/' . $v['group_url'])){
                        unlink(site_url() . '/' . $v['group_url']);
                    }
                }
                $sqldelete = 'Delete from ecm_group_goods where group_id = '.$v['activity_group_id'];
                $this->_group_goods_mod->db->query($sqldelete);
            }
            $sql = 'Delete from ecm_activity_group where activity_id = '.$activity_id;
            $this->_activity_group_mod->db->query($sql);
        }
        $this->show_message('删除成功');
    }

    //添加模块
    function add_group(){
        $activity_id = $_GET['activity_id']?$_GET['activity_id']:'';
        if(!$activity_id){
            $this->show_message('信息传递错误！');
            return false;
        }
        if(IS_POST){
            if($_FILES['group_url']['error'] == 4 || $_FILES['group_url']['size'] == 0){
                $this->show_message('请上传图片！');
                return false;
            }
            if(!$_POST['goods_id']){
                $this->show_message('请选择商品！');
                return false;
            }
            $sql = 'select max(group_id) as group_id from ecm_activity_group where activity_id = '.$activity_id;
            $info = $this->_activity_group_mod->db->query($sql);
            while ($chat = $this->_activity_group_mod->db->fetchRow($info)) {
                $chat_listOld = $chat;
            }
            $data = array(
                'activity_id'   => $activity_id,
                'group_id'      => $chat_listOld['group_id'] + 1,
                'sort_order'    => $_POST['sort_order'],
            );

            if (!$group_id = $this->_activity_group_mod->add($data)) {  //获取article_id
                $this->show_warning($this->_activity_group_mod->get_error());
                return;
            } else {
                $this->admin_log("新增分组h5", 1);
            }

            //处理上传的文章LOGO
            $article_logo = $this->_upload($_FILES,'group_url');
            if ($article_logo === false) {
                return;
            }
            //处理商品
            $goods_id = explode(',',$_POST['goods_id']);
            if(!empty($goods_id)){
                foreach($goods_id as $k=>$v){
                    $newArr['group_id'] = $chat_listOld['group_id'] + 1;
                    $newArr['goods_id'] = $v;
                    $newArr['sort_order'] = $_POST['goodsSorts'][$k];
                    $this->_group_goods_mod->add($newArr);
                }
            }

            $article_logo  && $this->_activity_group_mod->edit($group_id, array('group_url' => $article_logo)); //将logo地址记下

            $this->show_message('添加成功', 'back_list', 'index.php?app=promotional_activity',
                'continue_add', 'index.php?app=promotional_activity&amp;act=add_group&activity_id='.$activity_id
            );
        }else{
            $this->display('promotional_activity.add_group.html');
        }
    }

    //编辑分组中的商品
    function view_group(){
        $activity_group_id = $_GET['activity_group_id']?$_GET['activity_group_id']:'';
        if(!$activity_group_id){
            $this->show_message('数据错误！');
            return false;
        }
        $goods_spec = &m("goodsspec");
        $goods_mod = &m("goods");
        if(!IS_POST){
            $find_data = $this->_activity_group_mod->get($activity_group_id);
            $find_data['group_url'] = WEB_PHOTO_SRC.'/'.$find_data['group_url'];
            if (empty($find_data))
            {
                $this->show_warning('no_such_banner');
                return;
            }

            $sql = 'select * from ecm_group_goods where group_id = '.$find_data['group_id'];
            $query = $this->_group_goods_mod->db->query($sql);
            while ($chat = $this->_group_goods_mod->db->fetchRow($query)) {
                $goodsInfo[] = $chat;
            }
            $ids = '';
            foreach($goodsInfo as $k=>$v){
                if($k == 0){
                    $ids = $v['goods_id'];
                }else{
                    $ids .= ','.$v['goods_id'];
                }
                $in_array = array();
                $stock_array = array();
                $temp_goods[$k]['goods_id'] = $v['goods_id'];
                $c = $goods_mod->get($v['goods_id']);
                if(is_array($c) && $c){
                    $temp_goods[$k]['goods_name'] = $c['goods_name'];
                    $temp_goods[$k]['default_image'] = WEB_PHOTO_SRC  . "/" . $c['default_image'];

                }
                $temp_goods[$k]['sort_order'] = $v['sort_order'];
                $retult = $goods_spec->find(array('conditions'=>"goods_id = ".$v['goods_id']));
                //声明一个库存数
                $inventory = 0;
                foreach ($retult as $key => $vvalue) {
                    $inventory += $vvalue['stock'];
                }
                //总库存
                $temp_goods[$k]['total_inventory'] = $inventory;
                $temp_goods[$k]['times'] = $c['times']?$c['times']:"无";

                $res_ss = $goods_spec->getSpecStockInfo($v['goods_id']);
                foreach ($res_ss as $key => $value) {
                    $value['international_code'] && !in_array($value['international_code'],$in_array)  ?  $in_array[] = $value['international_code'] : NULL;
                    $value['stock_name'] && !in_array($value['stock_name'],$stock_array) ? $stock_array[] = $value['stock_name'] : NULL;
                    $res_ss[$key]['image'] = WEB_PHOTO_SRC  . "/" . $value['spec_1'];
                }
                $in_array ? $temp_goods[$k]['international_code'] = implode('<br>',$in_array) : NULL;
                $stock_array ? $temp_goods[$k]['stock_name'] = implode('<br>',$stock_array) : NULL;
                $temp_goods[$k]['specInfo'] = $res_ss;
            }
            $find_data['goods'] = $temp_goods;
            $this->assign('ids',$ids);
            $this->assign('info', $find_data);
            $this->display('promotional_activity.add_group.html');
        }else{
            $find_data     = $this->_activity_group_mod->get($activity_group_id);
            if (empty($find_data))
            {
                $this->show_warning('no_such_banner');
                return;
            }
            if(!$_POST['goods_id']){
                $this->show_message('请选择商品！');
                return false;
            }

            //删除原图片
            if($_FILES['group_url'] && $find_data['group_url'] && $find_data['group_url'] != $_FILES['group_url']){
                if(file_exists(site_url() . '/' . $find_data['group_url'])){
                    unlink(site_url() . '/' . $find_data['group_url']);
                }
            }

            $data = array(
                'sort_order' => $_POST['sort_order'],
            );
            $logo =   $this->_upload($_FILES,'group_url');
            $logo && $data['group_url'] = $logo;
            if ($logo === false)
            {
                $this->show_message('请上传图片！');
                return;
            }
            $rows=$this->_activity_group_mod->edit($activity_group_id, $data);
            if ($this->_activity_group_mod->has_error())
            {
                $this->show_warning($this->_activity_group_mod->get_error());
                return;
            }else{
                $sql = 'Delete from ecm_group_goods where group_id = '.$find_data['group_id'];
                $this->_group_goods_mod->db->query($sql);
                $this->admin_log("编辑活动H5",1);
            }

            //处理商品
            $goods_id = explode(',',$_POST['goods_id']);
            if(!empty($goods_id)){
                foreach($goods_id as $k=>$v){
                    $newArr['group_id'] = $find_data['group_id'];
                    $newArr['goods_id'] = $v;
                    $newArr['sort_order'] = $_POST['goodsSorts'][$k];
                    $this->_group_goods_mod->add($newArr);
                }
            }
            $this->show_message('编辑成功',
                '返回列表',        'index.php?app=promotional_activity',
                '再次编辑',    'index.php?app=promotional_activity&amp;act=view_group&amp;activity_group_id=' . $activity_group_id);
        }
    }
    //删除商品
    function view_drop(){
        $activity_group_id = isset($_GET['activity_group_id']) ? intval($_GET['activity_group_id']) : 0;
        if (!$activity_group_id)
        {
            $this->show_warning('no_such_banner');
            return;
        }
        $info = $this->_activity_group_mod->get(intval($activity_group_id));
        //删除原图片
        if($info['group_url']){
            if(file_exists(site_url() . '/' . $info['group_url'])){
                unlink(site_url() . '/' . $info['group_url']);
            }
        }
        if (!$this->_activity_group_mod->drop($activity_group_id)) {    //删除
            $this->show_warning($this->_activity_group_mod->get_error());
            return;
        }else{
            $sqldelete = 'Delete from ecm_group_goods where group_id = '.$activity_group_id;
            $this->_group_goods_mod->db->query($sqldelete);
        }
        $this->show_message('删除成功');
    }


    function _upload($file,$str){
        require_once '../includes/aliyunOss/samples/Common.php';
        $image = $file[$str];
        $imageName = date("YmdHis", time()) . rand(1000,10000);
        $path = 'data/files/mall/promotional_activity/'.$str;

        if ($image['error'] == UPLOAD_ERR_NO_FILE) { // 没有文件被上传
            return '';
        }
        import('uploader.lib');             //导入上传类
        $uploader = new Uploader();
        $uploader->allowed_type(IMAGE_FILE_TYPE); //限制文件类型
        $uploader->addFile($_FILES[$str]); //上传logo
        if (!$uploader->file_info()) {
            $this->show_warning($uploader->get_error(), 'go_back', 'index.php?app=promotional_activity&amp;act=index');
            return false;
        }
        /* 指定保存位置的根目录 */
        $uploader->root_dir(ROOT_PATH);
        if (!$file_path = $uploader->save($path,$imageName)) {   //保存到指定目录，并以指定文件名$ad_id存储
            $this->show_message('上传文件失败！');
            return false;
        }
        $ossClient = new \common;
        $r = $ossClient->putObjectFile('../'.$file_path,$file_path);
        if(!$r['info'] || $r['info']['http_code'] != 200){
            $this->show_message('上传oss失败！');
            return false;
        }
        unlink('../'.$file_path);
        return $file_path;
    }


}